package com.wy.tingshu.servlet.publish;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wy.tingshu.util.DBUtil;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * 公开的页面——普通用户直接可以看到的页面（页面中有已上线的专辑列表），给首页用的
 * ps:创作中心属于未公开的，登陆后才可以看到
 **/
@WebServlet("/album-list.json")
public class AlbumListServlet extends HttpServlet {
    private static class AlbumView{
        public Integer aid;
        public String username;
        public String title;
        public String cover;

        @SneakyThrows
        public AlbumView(ResultSet rs) {
            this.aid = rs.getInt("aid");
            this.username = rs.getString("username");
            this.title = rs.getString("title");
            this.cover = rs.getString("cover");
        }
    }

    private static class ResultView{
       public  List<AlbumView> albumList=new ArrayList<>();
    }
    //该页无需验证登录
    //普通用户可以在首页查看的所有已发布的专辑列表。通过连表查询做到：专辑表和用户表连表操作
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ResultView resultView=new ResultView();
        try (Connection c= DBUtil.connection()){
            String sql="select aid,username,title,cover from albums a join users u on a.uid=u.uid where state = 2 order by aid desc";
            try (PreparedStatement ps=c.prepareStatement(sql)){
                try (ResultSet rs= ps.executeQuery()){
                    while (rs.next()){
                        AlbumView view = new AlbumView(rs);
                        resultView.albumList.add(view);
                    }
                }
            }
        }
        //转JSON
        ObjectMapper objectMapper=new ObjectMapper();
        String json = objectMapper.writeValueAsString(resultView);
        //响应
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        resp.getWriter().println(json);
    }
}
